import { Navigate, useLocation } from 'react-router-dom'
import PropTypes from 'prop-types'
import storage from '@/libs/storage'

const PrivateRoute = ({ children }) => {
  const location = useLocation()
  const isAuthenticated = storage.get('token')
  const redirectPath = location.pathname || '/'

  if (!isAuthenticated) {
    // 需要认证但未登录，重定向到登录页
    return <Navigate to={`/login?redirect=${redirectPath}`} state={{ from: redirectPath }} replace />
  }

  return <>{children}</>
}

// 添加 props 验证
PrivateRoute.propTypes = {
  children: PropTypes.node.isRequired // 定义 children 为必需的节点类型
}

export default PrivateRoute